<template>
	<view class="preview" v-if="currentInfo">
		<!-- :current绑定currentIndex，以便currentIndex随着滑动改变 -->
		<swiper circular :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(item,index) in classList" :key="item._id">
				<!-- currentIndex === index，看一张，加载一张图片，以减少流量消耗 -->
				<image v-if="currentIndex === index" @click="maskChange" :src="item.picurl" mode="aspectFill"></image>
				<!-- 同时加载临近图片：Math.abs(currentIndex - index) <= 1 -->
				<!-- 还是有缺陷：看第一张或最后一张时，最后一张或第一张要完全滑过才能加载 -->
				<!-- <image v-if="Math.abs(currentIndex - index) <= 1" @click="maskChange" :src="item.picurl" mode="aspectFill"></image> -->
				<image v-if="readImgs.includes(index)" @click="maskChange" :src="item.picurl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		
		<view v-show="maskVisible" class="mask">
			<!-- 兼容：抖音小程序自带返回按钮，所以在非抖音小程序才有这个返回 -->
			#<!-- #ifndef MP-TOUTIAO -->
			<view @click="goBack" class="goBack" :style="{top:getStatusBarHeight()+'px'}">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>
			</view>
			<!-- #endif -->
			<view class="count">{{currentIndex + 1}} / {{classList.length}}</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<!-- 这里使用 v-if 是因为代码执行顺序问题，currentInfo 一开始是空值，所以报错，但后来又重新赋值了，所以可以正确渲染出来 -->
			<!-- 还有一个解决方案：ref声明数据时不用null，使用空对象或空数组 -->
			<!-- 已将v-if放到最外层盒子 -->
			<view class="footer">
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="text">{{currentInfo.score}}分</view>
				</view>
				<view @click="clickDownload" class="box">
					<uni-icons type="download" size="28"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		
		<uni-popup :safe-area="false" ref="infoPopup" type="bottom">
			<view class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view @click="clickInfoClose" class="close">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y>
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID：</view>
							<text selectable class="value">{{currentInfo._id}}</text>
						</view>
						<!-- <view class="row">
							<view class="label">分类：</view>
							<text class="value class">明星美女</text>
						</view> -->
						<view class="row">
							<view class="label">发布者：</view>
							<text class="value">{{currentInfo.nickname}}</text>
						</view>
						<view class="row">
							<view class="label">评分：</view>
							<view class="value rateBox">
								<uni-rate readonly :value="currentInfo.score" size="16"/>
								<text class="score">{{currentInfo.score}}分</text>
							</view>
						</view>
						<view class="row">
							<view class="label">摘要：</view>
							<text class="value">{{currentInfo.description}}</text>
						</view>
						<view class="row">
							<view class="label">标签：</view>
							<view class="value tags">
								<view class="tag" v-for="item in currentInfo.tabs" :key="item">{{item}}</view>
							</view>
						</view>
						<view class="copywright">声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		
		<uni-popup ref="scorePopup" :is-mask-click="false">
			<view class="scorePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">{{isScore?'已评分过了~':'壁纸评分'}}</view>
					<view @click="clickScoreClose" class="close">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				
				<view class="content">
					<uni-rate :disabled="isScore" disabled-color="#ffca3e" v-model="userScore" allow-half />
					<text class="text">{{userScore}}分</text>
				</view>
				
				<view class="footer">
					<button @click="submitScore" :disabled="!userScore || isScore" type="default" size="mini" plain>确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { getStatusBarHeight } from '@/utils/system.js'
import { apiGetSetupScore, apiWriteDownload, apiDetailWall } from '@/api/apis.js'

const isScore = ref(false) // 判断是否已经评分

// 获取缓存的数据
const classList = ref([])
const storageClassList = uni.getStorageSync('storageClassList') || []
classList.value = storageClassList.map(item => {
	return {
		...item,
		// 把 _small.webp 替换成 .jpg
		picurl: item.smallPicurl.replace('_small.webp', '.jpg')
	}
})
// console.log(storageClassList)

const currentId = ref(null)
const currentIndex = ref(0)
const currentInfo = ref(null) // 壁纸信息
onLoad(async (e) => {
	currentId.value = e.id
	if (e.type === 'share') {
		// 说明是通过分享过来的
		const res = await apiDetailWall({id: currentId.value})
		// console.log(res)
		classList.value = res.data.map(item => {
			return {
				...item,
				// 把 _small.webp 替换成 .jpg
				picurl: item.smallPicurl.replace('_small.webp', '.jpg')
			}
		})
	}
	currentIndex.value = classList.value.findIndex(item => item._id === currentId.value)
	// console.log(currentIndex.value)
	currentInfo.value = classList.value[currentIndex.value]
	readImgsFn()
})

const readImgs = ref([]) // 已看过的图片数组
const swiperChange = (e) => {
	// console.log(e)
	currentIndex.value = e.detail.current
	currentInfo.value = classList.value[currentIndex.value]
	readImgsFn()
}

const readImgsFn = () => {
	readImgs.value.push(
		currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1, 
		currentIndex.value, 
		currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1
	)
	readImgs.value = [...new Set(readImgs.value)]
}

// 点击下载
const clickDownload = async () => {
	// h5兼容
	// #ifdef H5
	uni.showModal({
		content: '请长按保存壁纸',
		showCancel: false
	})
	// uni.showToast({
	// 	title: '请长按保存壁纸',
	// 	icon: 'none'
	// })
	// #endif
	
	// #ifndef H5
	// 异步同步化的错误放到catch里面
	try {
	uni.showLoading({
		title: '下载中...',
		mask: true
	})
	
	// 一定时间内只能下载一次
	const { classid, _id:wallId } = currentInfo.value
	const res = await apiWriteDownload({
		classid,
		wallId
	})
	if (res.errCode !== 0) throw res
	// return console.log(res)
	// getImageInfo生成临时下载地址，需要配置白名单
	// mp.weixin.qq.com - 开发管理 - 开发设置 - 服务器域名 - downloadFile合法域名
	// 填入：https://mp-0cb878b7-99ec-44ea-8246-12b123304b05.cdn.bspapp.com
	uni.getImageInfo({
		src: currentInfo.value.picurl,
		success: res => {
			console.log(res)
			uni.saveImageToPhotosAlbum({
				filePath: res.path,
				success: res => {
					console.log(res)
				},
				fail: (err) => {
					// console.log(err)
					// 已获得授权但取消保存的情况
					if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
						uni.showToast({
							title: '保存失败，请重新点击下载',
							icon: 'none'
						})
						return
					}
					// 未获得授权的情况
					uni.showModal({
						title: '提示',
						content: '需要授权访问相册',
						success: res => {
							if (res.confirm) {
								// console.log('确认授权')
								uni.openSetting({
									success: (setting) => {
										console.log(setting)
										if (setting.authSetting['scope.writePhotosAlbum']) {
											uni.showToast({
												title: '获取授权成功',
												icon: 'none'
											})
										} else {
											uni.showToast({
												title: '获取授权失败',
												icon: 'none'
											})
										}
									}
								})
							}
						}
					})
				},
				complete: () => {
					uni.hideLoading()
				}
			})
		},

	})
	} catch (err) {
		console.log(err)
		uni.hideLoading()
	}
	// #endif
}

// .mask遮罩层状态
const maskVisible = ref(true)
const scorePopup = ref(null)
const userScore = ref(0)
const maskChange = () => {
	maskVisible.value = !maskVisible.value
}
// 点击评分
const clickScore = () => {
	if (currentInfo.value.userScore){
		isScore.value = true
		userScore.value = currentInfo.value.userScore // 显示评分过的分数
	}
	scorePopup.value.open()
}
// 关闭评分弹窗
const clickScoreClose = () => {
	scorePopup.value.close()
	userScore.value = 0
	isScore.value = false
}
// 确认评分
const submitScore = async () => {
	uni.showLoading({
		title: '加载中...'
	})
	// console.log(currentInfo.value)
	// console.log(userScore.value)
	const { classid, _id:wallId } = currentInfo.value
	const res = await apiGetSetupScore({
		classid,
		wallId,
		userScore: userScore.value
	})
	// console.log(res)
	uni.hideLoading()
	if (res.errCode === 0) {
		uni.showToast({
			title: '评分成功',
			icon: 'none'
		})
		classList.value[currentIndex.value].userScore = userScore.value
		uni.setStorageSync('storageClassList', classList.value)
		clickScoreClose()
	}
}

// 点击info弹窗
// 绑定元素
const infoPopup = ref(null)
const clickInfo = () => {
	infoPopup.value.open()
}
// 点击关闭弹窗信息
const clickInfoClose = () => {
	infoPopup.value.close()
}

// 左上角箭头返回上一页
const goBack = () => {
	uni.navigateBack({
		success: () => {
			
		},
		fail: (err) => {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}
	})
}

// 分享给好友
onShareAppMessage((e) => {
	// console.log(e)
	return {
		title: '咸虾米壁纸', // 标题
		// 因为别人点击的时候大概率没有storage缓存，所以需要去接口获取数据
		path: `pages/preview/preview?id=${currentId.value}&type=share` // 点击分享到哪个页面
	}
})

// 分享到朋友圈
onShareTimeline(() => {
	return {
		title: '咸虾米壁纸', // 标题
		// imageUrl: '/static/images/logo2.jpg' // 分享的链接的图片
		query: `id=${queryParams.classid}&type=share`
	}
})

</script>

<style lang="scss" scoped>
.preview {
	position: relative;
	width: 100%;
	height: 100vh;
	swiper {
		width: 100%;
		height: 100%;
		image {
			width: 100%;
			height: 100%;
		}
	}
	
	.mask {
		// 直接子元素且是view的标签
		&>view {
			position: absolute;
			left: 0;
			right: 0;
			margin: auto;
			// l0+r0+m-auto+w-fit-content构成内容水平居中的效果，宽度由内容填充
			width: fit-content;
			color: #fff;
		}
		.goBack {
			display: flex;
			justify-content: center;
			align-items: center;
			left: 30rpx;
			top: 0;
			margin-left: 0;
			width: 38px;
			height: 38px;
			background: rgba(0,0,0,0.5);
			border: 1px solid rgba(255,255,255,0.3);
			border-radius: 100px;
			backdrop-filter: blur(10rpx);
		}
		.count {
			top: 10vh;
			padding: 8rpx 28rpx;
			font-size: 28rpx;
			background-color: rgba(0,0,0,.3);
			border-radius: 40rpx;
			backdrop-filter: blur(10rpx);
		}
		.time {
			top: calc(10vh + 80rpx);
			font-size: 140rpx;
			font-weight: 100;
			line-height: 1em;
			text-shadow: 0 4rpx rgba(0,0,0,.3);
		}
		.date {
			top: calc(10vh + 230rpx);
			font-size: 34rpx;
			text-shadow: 0 2rpx rgba(0,0,0,.3);
		}
		.footer {
			display: flex;
			justify-content: space-around;
			align-items: center;
			bottom: 10vh;
			width: 65vw;
			height: 120rpx;
			color: #000;
			border-radius: 120rpx;
			background: rgba(255,255,255,.8);
			box-shadow: 0 2rpx 0 rgba(0,0,0,.1);
			backdrop-filter: blur(20rpx);
			.box {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				// text-align: center;
				// line-height: 1;
				// 增大点击范围
				padding: 2rpx 12rpx;
				.text {
					font-size: 26rpx;
					color: $text-font-color-2;
				}
			}
		}
	}

	// infoPopup和scorePopup共用头部样式
	.popHeader {
		display: flex;
		justify-content: space-between;
		align-items: center;
		.title {
			color: $text-font-color-2;
			font-size: 26rpx;
		}
		.close {
			padding: 6rpx;
		}
	}

	.infoPopup {
		padding: 30rpx;
		background-color: #fff;
		border-radius: 30rpx 30rpx 0 0;
		overflow: hidden;
		
		scroll-view {
			max-height: 60vh;
			.content {
				.row {
					display: flex;
					align-items: center;
					padding: 16rpx 0;
					font-size: 32rpx;
					line-height: 1.7em;
					.label {
						color: $text-font-color-3;
						width: 140rpx;
						font-size: 30rpx;
						text-align: right;
					}
					.value {
						flex: 1;
						// 设置text内容的初始宽度为0，防止因text内容过多挤压.lable
						width: 0;
					}
					.rateBox {
						display: flex;
						align-items: center;
						.score {
							padding-left: 10rpx;
							font-size: 26rpx;
							color: $text-font-color-2;
						}
					}
					.tags {
						display: flex;
						flex-wrap: wrap;
						.tag {
							margin: 0 10rpx 10rpx 0;
							padding: 10rpx 30rpx;
							font-size: 22rpx;
							color: $brand-theme-color;
							line-height: 1em;
							border: 1px solid $brand-theme-color;
							border-radius: 40rpx;
						}
					}
					.class {
						color: $brand-theme-color;
					}
				}
				.copywright {
					margin: 20rpx 0;
					padding: 20rpx;
					font-size: 28rpx;
					color: #666;
					line-height: 1.6em;
					background: #F6F6F6;
					border-radius: 10rpx;
				}
			}
		}
	}

	.scorePopup {
		padding: 30rpx;
		width: 70vw;
		background-color: #fff;
		border-radius: 30rpx;
		.content {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 30rpx 0;
			.text {
				padding-left: 10rpx;
				width: 80rpx;
				font-size: 28rpx;
				color: #FFCA3E;
				line-height: 1em;
				text-align: right;
			}
		}
		.footer {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 10rpx 0;
		}
	}
}
</style>
